using System;
using System.Web;
using System.Web.UI.WebControls;
using Activa.CoolStorage;
using CodeStory.Core.ObjectBusiness;
using CodeStory.Core;
using CodeStory.Core.ObjectEntity;
using CodeStory.Core.Providers;
using CodeStory.Core.UI;
using CodeStory.WebControls;

namespace CodeStory.WebApplication.Modules.Core.Admin
{
	[NavigationPortlet("CodeStory_Core_Admin_ChooseLayout")]
	public partial class ChooseLayout : Portlet
	{

		protected override void OnInit(EventArgs e) {
			Load += new EventHandler(ChooseLayout_Load);
			btnNext.Click += new EventHandler(ButtonNext_Click);
			base.OnInit(e);
		}

	

		private void ButtonNext_Click(object sender, EventArgs e) {
			string layoutid = string.Empty;
			foreach (RepeaterItem item in layoutRepeater.Items) {
				RadioButton rbtn = item.FindControl("radio") as RadioButton;
				if (rbtn != null && rbtn.Checked) {
					Label lbl = item.FindControl("lblLayoutID") as Label;
					if (lbl != null) {
						layoutid = lbl.Text;
						break;
					}
				}
			}
			if (string.IsNullOrEmpty(layoutid)) {
				return;
			}
			string id = Request.QueryString["editpageid"];
			Guid pageid;
			if (string.IsNullOrEmpty(id)) {
				pageid = PageBusiness.InsertPage(txtPageName.Text,txtTitle.Text,"",new Guid(layoutid));
			} else {
				pageid = PageBusiness.UpdatePage(new Guid(id), txtPageName.Text, txtTitle.Text,"", new Guid(layoutid));
			}
			Navigate(typeof(CreatePage), "editpageid=" + pageid);
		}


		private void ChooseLayout_Load(object sender, EventArgs e) {
			if (!IsPostBack && !EditMode) {
				BindLayouts();
				BindEditPageObject();
			}
		}

		private void BindEditPageObject() {
			string pageid = Request.QueryString["editpageid"];
			if (string.IsNullOrEmpty(pageid)) {
				return;
			}
			PageObject page = PageObject.Read(new Guid(pageid));
			txtPageName.Text = page.PageName;
			txtTitle.Text = page.Title;

			string layoutid = page.LayoutID.ToString();
			SetSelectedLayout(layoutid);
		}

		private void SetSelectedLayout(string layoutid) {
			foreach (RepeaterItem item in layoutRepeater.Items) {
				Label lbl = item.FindControl("lblLayoutID") as Label;
				if (lbl != null) {
					if (string.Equals(lbl.Text, layoutid, StringComparison.OrdinalIgnoreCase)) {
						GroupRadioButton r = item.FindControl("radio") as GroupRadioButton;
						if (r != null) {
							r.Checked = true;
							break;
						}
					}
				}
			}
		}



		private void BindLayouts() {
			layoutRepeater.DataSource = LayoutBusiness.GetAllLayouts();
			layoutRepeater.DataBind();
		}
	}
}